<template>
  <label class="ee-switch" :active="checked ? '' : undefined" @click="click" @keydown.enter="click" tabindex="0"
         :style="{ '--ee-switch-color0': color0, '--ee-switch-color1': color1 }">
    <input v-if="name" type="hidden" :name="name" :value="modelValue" /><template v-else />
    <template v-if="text0">
      <span :active="!checked ? '' : undefined">{{ text0 }} </span>&nbsp;
    </template><template v-else />
    <a class="strip">
      <i>
        <slot></slot>
      </i>
    </a>
    <template v-if="text1">
      &nbsp;<span :active="checked ? '' : undefined"> {{ text1 }}</span>
    </template><template v-else />
  </label>
</template>

<script type="text/javascript">
import { injectStore } from 'ee-vuex'
import { formProps } from './index'
import { emits } from '../__mixin/select/radio';

export default injectStore({
  name: "ee-switch",
  emits,
  props: {
    ...formProps,
    /** 关时背景条颜色，可通过样式--ee-switch-color0设置 */
    color0: String,
    /** 开时背景条颜色，可通过样式--ee-switch-color1设置 */
    color1: String,
    /** 关时按钮上的文字，可通过插槽<slot #default="{ checked }">设置 */
    text0: String,
    /** 开时按钮上的文字，可通过插槽<slot #default="{ checked }">设置 */
    text1: String,
    /** 关时的值，默认 false */
    value0: { default: () => false },
    /** 开时的值，默认 true */
    value1: { default: true },
    /** 开关的值 */
    modelValue: false,
    /** 开关的状态 */
    checked: {
      type: Boolean,
      get() {
        const value = this.modelValue == this.value1;
        // 同步 modelValue 的值
        this.checked = value;
        return value;
      },
      set(value, set) {
        if (value)
          this.modelValue = this.value1;
        else
          this.modelValue = this.value0;
        // 触发事件
        set(value);
        this.$emit("change", value, this);
        if (value)
          this.$emit("check", this);
      }
    }
  },
  methods: {
    click() {
      this.checked = !this.checked;
    }
  },
})
</script>

<style lang="scss">
.ee-switch {
  cursor: pointer;

  > span[active] {
    color: var(--ee-switch-color1);
  }

  &[active] {
    .strip {
      color: var(--ee-switch-color1);

      & > i {
        left: 50%;
      }
    }
  }

  .strip {
    display: inline-block;
    width: 2.4em;
    height: 1.25em;
    padding: .125em;
    border-radius: 1em;
    color: var(--ee-switch-color0);
    background-color: currentColor;
    cursor: pointer;
    transition: color var(--ee-transition-duration);
    vertical-align: middle;

    & > i {
      display: block;
      width: 50%;
      height: 1em;
      line-height: 1em;
      border-radius: .5em;
      background-color: var(--ee-bgcolor);
      transition: left var(--ee-transition-duration);
      position: relative;
      left: 0;
      text-align: center;
    }
  }
}
</style>